package org.ehe.business.workstation.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ehe.business.workstation.domain.bo.WorkstationBo;
import org.ehe.business.workstation.domain.vo.WorkstationVo;
import org.ehe.business.workstation.service.IWorkstationService;
import org.ehe.business.workstation.service.NonStandardPartImportService;
import org.ehe.business.workstation.service.WorkstationCodeService;
import org.ehe.common.core.domain.R;
import org.ehe.common.log.annotation.Log;
import org.ehe.common.log.enums.BusinessType;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 工位管理控制器
 *
 * @author zhangnn
 * @date 2025-10-23
 */
@Slf4j
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/business/workstation")
public class WorkstationController {

    private final IWorkstationService workstationService;
    private final WorkstationCodeService codeService;
    private final NonStandardPartImportService importService;

    /**
     * 分页查询工位列表
     */
    @SaCheckPermission("business:workstation:query")
    @GetMapping("/list")
    public TableDataInfo<WorkstationVo> list(WorkstationBo bo, PageQuery pageQuery) {
        return workstationService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询所有工位列表(不分页)
     */
    @SaCheckPermission("business:workstation:query")
    @GetMapping("/listAll")
    public R<List<WorkstationVo>> listAll(WorkstationBo bo) {
        return R.ok(workstationService.queryList(bo));
    }

    /**
     * 新增工位
     */
    @SaCheckPermission("business:workstation:add")
    @Log(title = "工位管理", businessType = BusinessType.INSERT)
    @PostMapping()
    public R<Void> add(@Validated @RequestBody WorkstationBo bo) {
        boolean result = workstationService.insertWorkstation(bo);
        return result ? R.ok("新增成功") : R.fail("新增失败");
    }

    /**
     * 修改工位
     */
    @SaCheckPermission("business:workstation:edit")
    @Log(title = "工位管理", businessType = BusinessType.UPDATE)
    @PutMapping()
    public R<Void> edit(@Validated @RequestBody WorkstationBo bo) {
        boolean result = workstationService.updateWorkstation(bo);
        return result ? R.ok("修改成功") : R.fail("修改失败");
    }

    /**
     * 删除工位
     */
    @SaCheckPermission("business:workstation:remove")
    @Log(title = "工位管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@PathVariable Long[] ids) {
        boolean result = workstationService.deleteWorkstations(Arrays.asList(ids));
        return result ? R.ok("删除成功") : R.fail("删除失败");
    }

    /**
     * 生成设备编码
     * 格式: 03.工位code.设备号
     * 示例: 03.001.000001
     */
    @GetMapping("/generateCode")
    public R<Map<String, Object>> generateCode(
            @RequestParam String workstationCode,
            @RequestParam(required = false, defaultValue = "新设备") String deviceName) {
        try {
            WorkstationCodeService.CodeGenerateResult result = codeService.generateCode(workstationCode, deviceName);

            if (result.isSuccess()) {
                Map<String, Object> data = new HashMap<>();
                data.put("workstationCode", result.getWorkstationCode());
                data.put("deviceCode", result.getDeviceCode());
                data.put("fullCode", result.getFullCode());
                data.put("deviceName", result.getDeviceName());
                data.put("fullName", result.getFullName());
                data.put("sequenceNo", result.getSequenceNo());
                data.put("preview", String.format("工位：%s，设备序号：%d，完整编码：%s",
                        result.getWorkstationCode(), result.getSequenceNo(), result.getFullCode()));

                return R.ok(result.getMessage(), data);
            } else {
                return R.fail(result.getMessage());
            }
        } catch (Exception e) {
            log.error("生成设备编码失败", e);
            return R.fail("生成编码失败：" + e.getMessage());
        }
    }

    /**
     * 导入非标件Excel
     */
    @SaCheckPermission("business:workstation:import")
    @Log(title = "非标件导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importNonStandard")
    public R<String> importNonStandard(@RequestParam("file") MultipartFile file,
            @RequestParam(value = "importId", required = false) Long importId) {
        try {
            if (file.isEmpty()) {
                return R.fail("请选择要导入的Excel文件");
            }

            String fileName = file.getOriginalFilename();
            if (fileName == null || !(fileName.endsWith(".xlsx") || fileName.endsWith(".xlsm"))) {
                return R.fail("请上传.xlsx或.xlsm格式的Excel文件");
            }

            // 如果没有提供importId，生成一个
            if (importId == null) {
                importId = System.currentTimeMillis();
            }

            NonStandardPartImportService.ImportResult result = importService.importExcel(file, importId);

            if (result.getFailureRows() == 0) {
                return R.ok(result.getMessage());
            } else {
                return R.warn(result.getDetailMessage());
            }

        } catch (Exception e) {
            log.error("导入非标件失败", e);
            return R.fail("导入失败：" + e.getMessage());
        }
    }
}
